package com.tarena.lbs.basic.web.service;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.BasePageList;
import com.tarena.lbs.basic.web.filter.UtilsThreadLocal;
import com.tarena.lbs.basic.web.repository.AdminRepository;
import com.tarena.lbs.common.basic.enums.BasicResultEnum;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.common.security.utils.LbsSecurityContenxt;
import com.tarena.lbs.pojo.basic.bo.AdminBO;
import com.tarena.lbs.pojo.basic.dos.AdminDO;
import com.tarena.lbs.pojo.basic.dto.AdminDTO;
import com.tarena.lbs.pojo.basic.po.AdminPO;
import com.tarena.lbs.pojo.basic.query.AdminQuery;
import com.tarena.lbs.pojo.basic.vo.AdminVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class AdminService {
    @Autowired
    private AdminRepository adminRepository;
    public AdminVO adminDeatil() throws BusinessException {
       Integer adminId = getLoginUserId();
       AdminBO adminBO = adminRepository.getAdminById(adminId);
       AdminVO adminVO = new AdminVO();
        if (adminBO == null) {
            throw new BusinessException(BasicResultEnum.ADMIN_NOTEXISTS);
        }
        BeanUtils.copyProperties(adminBO,adminVO);
       return adminVO;
    }

    public AdminBO adminDetail(Integer adminId) throws BusinessException{
        //2. 调用仓储层 查询数据 select * from lbs_admin where id=#{id}
        AdminBO adminBO=adminRepository.getAdminById(adminId);
        //3. 返回数据
        return adminBO;
    }


    private Integer getLoginUserId() throws BusinessException {
        //1.使用threadlocal获取 现成中存储的user数据
//        UserPrinciple userPrinciple = LbsSecurityContenxt.getLoginToken();
        UtilsThreadLocal utilsThreadLocal = new UtilsThreadLocal();
        UserPrinciple userPrinciple = utilsThreadLocal.getValue();
        log.info("从threadlocal中获取的数据:{}",userPrinciple);
        //2/验证非空 才获取id返回
        if (ObjectUtils.isEmpty(userPrinciple)){
            throw new BusinessException("102","登录用户数据不存在");
        }
        return userPrinciple.getId();
    }

    public BasePageList<AdminBO> adminList(AdminQuery adminQuery) {
        return adminRepository.adminList(adminQuery);
    }

    public void adminSave(AdminBO param) throws BusinessException{
        log.info("当前新增商家账号入参:{}",param);
        //select count(*) from lbs_admin where account_phone=#{phone}
        long total = adminRepository.AdminCountByPhone(param.getAccountPhone());
        if (total>0){
            throw new BusinessException("104","手机号已存在");
        }
        param.setCreateTime(new Date());
        adminRepository.save(param);
    }

}
